﻿//#include "sys_inc.h"
#include "ff.h"
#include "ebook_api.h"
#include "ebook_init.h"
#include "ebook_util.h"

int ebook_init(
	char * fname,
	char * fidx,
	EBOOK_cb cb,
	int default_format	//default_format：ANSI_FORMAT==国标码优先；others==utf8优先
	)					//返回 -1==失败；others起始page；
{
	ebook_free();

	hebook = (EBOOK_CONTENT*)MALLOC(sizeof(EBOOK_CONTENT));
	memset(hebook, 0, sizeof(EBOOK_CONTENT));
	hebook->version = EBOOK_VERSION;
	strcpy(hebook->fname, fname);
	strcpy(hebook->fidx, fidx);
	hebook->cb = cb;

	hebook->default_format = default_format;

	if(0 != init_())
	{
		ebook_free();
		return -1;
	}

	hebook->cb(hebook->pages);

	return hebook->page;
}

void ebook_free()
{
	if(hebook)
	{
		unsigned br = 0;

		close_task();

		if(hebook->f_idx)
		{
			f_lseek(hebook->f_idx, 0);
			f_write(hebook->f_idx, hebook, sizeof(INDEX_HEAD), &br);
		}
		ffclose(&hebook->f_txt);
		ffclose(&hebook->f_idx);
		FREE(hebook);
		hebook = 0;
	}
}

int ebook_get_page(int page, unsigned char ** ptxt)
{
	if(hebook == 0)
	{
		return -1;
	}

	hebook->page = page;
	*ptxt = hebook->utf8_txt;

	return get_page();
}
